package com.kldy8.kldyw;

import android.app.ActivityManager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BadgeItem;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.kldy8.kldyw.logre.LoginActivity;
import com.kldy8.kldyw.release.activity.ReleaseMainActivity;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;
import com.kldy8.kldyw.tools.BackHandledFragment;
import com.kldy8.kldyw.tools.BackHandledIntegerface;
import com.mcxiaoke.bus.Bus;
import com.mcxiaoke.bus.annotation.BusReceiver;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Request;

/**
 * 第二版主页
 */
public class Main2Activity extends  BaseActivity implements BottomNavigationBar.OnTabSelectedListener  ,BackHandledIntegerface {
    /**
     * DrawerLayout
     */
    private DrawerLayout mDrawerLayout;

    private ListView mMenuListView;
    /**
     * 右边栏
     */
    private RelativeLayout right_drawer;
    /**
     * 菜单列表
     */
    private String[] mMenuTitles;

    /**
     * 右边栏打开/关闭状态
     */
    private boolean isDirection_right = false;

    private BottomNavigationBar bottomNavigationBar;

    int lastSelectedPosition = 0;


    //    private HomePageFragmentIII mHomePageFragment;

    /**
     * //个人
     * private MineFragment mMineFragment;
     * //企业
     * private MineGSFragment mMinebgFragment;
     * <p>
     * private Toolbar toolbar;
     * private ImageButton release_btn;
     **/

    private WebCircleFriendsFragment mWebCircleFriendsFragment;
    private FilmFactoryFragment mFilmFactoryFragment;
    private FindFragment findFragment;
    private Mine2Fragment mMineFragment;

    private BottomNavigationItem mineItem;
    private BadgeItem numberBadgeItem;
    private ImageView release;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Bus.getDefault().register(this);
        release= (ImageView) findViewById(R.id.release);
        release.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), ReleaseMainActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
            }
        });

        bottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);
        bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);

        mineItem = new BottomNavigationItem(R.drawable.icon_my, getResources().getString(R.string.mine));
        numberBadgeItem = new BadgeItem().setBackgroundColor(android.R.color.transparent);
        mineItem.setBadgeItem(numberBadgeItem);

        bottomNavigationBar
                .addItem(new BottomNavigationItem(R.drawable.icon_index, getResources().getString(R.string.home_page)))
                .addItem(new BottomNavigationItem(R.drawable.icon_make, getResources().getString(R.string.make)))
                .addItem(new BottomNavigationItem(R.drawable.icon_tabcenter_android, getResources().getString(R.string.fb)))
                .addItem(new BottomNavigationItem(R.drawable.icon_find, getResources().getString(R.string.find)))
                .addItem(mineItem).setActiveColor(R.color.colorAccent)
                .setFirstSelectedPosition(lastSelectedPosition)
                .initialise();

        bottomNavigationBar.setTabSelectedListener(this);
        setDefaultFragment();

        //侧边栏
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//        right_drawer = (RelativeLayout) findViewById(R.id.right_drawer);

        setMessageIcon();
    }

    /**
     * 回调  处理
     *
     * @param event
     */
    @BusReceiver
    public void onStringEvent(String event) {
        if (event.equals("10004") || event.equals("10000")|| event.equals("10005")) {
            SystemSet.getInstance().clean(getApplication());
            SystemSet.getInstance().removeContextAllCookie(this);
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
//        if (item.getItemId() == R.id.action_action)
//        {
//            mDrawerLayout.openDrawer(right_drawer);
//            Intent intent = new Intent();
//            intent.setClass(this, ReleaseMainActivity.class);
//            startActivity(intent);
//            overridePendingTransition(R.anim.push_bottom_in,R.anim.push_bottom_out);
//            return true ;
//        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 设置默认的
     */
    private void setDefaultFragment() {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        mWebCircleFriendsFragment = WebCircleFriendsFragment.newInstance("首页");
        transaction.replace(R.id.tb, mWebCircleFriendsFragment);
        transaction.commit();
    }

    @Override
    public void onTabSelected(int position) {
        if (numberBadgeItem != null) {
            hideBrbtn();
        }
        FragmentManager fm = this.getFragmentManager();
        //开启事务
        FragmentTransaction transaction = fm.beginTransaction();
        switch (position) {
            case 0:
                if (mWebCircleFriendsFragment == null) {
                    mWebCircleFriendsFragment = WebCircleFriendsFragment.newInstance(getResources().getString(R.string.home_page));
                }
                transaction.replace(R.id.tb, mWebCircleFriendsFragment);
                break;
            case 1:
                if (mFilmFactoryFragment == null) {
                    mFilmFactoryFragment = FilmFactoryFragment.newInstance(getResources().getString(R.string.make));
                }
                transaction.replace(R.id.tb, mFilmFactoryFragment);
                break;
            case 2:
                Intent intent = new Intent();
                intent.setClass(this, ReleaseMainActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
                recreate();
                break;
            case 3:
                if (findFragment == null) {
                    findFragment = FindFragment.newInstance(getResources().getString(R.string.find));
                }
                transaction.replace(R.id.tb, findFragment);
                break;
            case 4:
                String token = "" + SystemSet.getInstance().getToken();
                if (token == null || ("".equals(token))) {
                    Intent intent2 = new Intent();
                    intent2.setClass(this, LoginActivity.class);
                    startActivity(intent2);
                    overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                    recreate();
                    break;
                } else {
                    if (mMineFragment == null) {
                        mMineFragment = Mine2Fragment.newInstance(getResources().getString(R.string.mine));
                    }
                    transaction.replace(R.id.tb, mMineFragment);
                    break;
                }

            default:
                break;
        }
        // 事务提交
        transaction.commit();
    }

    @Override
    public void onTabUnselected(int position) {

    }

    @Override
    public void onTabReselected(int position) {

    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main2, menu);
//        MenuItem menuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
//        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
//        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//
//            public boolean onQueryTextSubmit(String query) {
//                Log.e("tag", query);
//                Intent intent = new Intent(Main2Activity.this, SearchActivity.class);  //方法1
//                Bundle bundle = new Bundle();
//                String[] languages = getResources().getStringArray(R.array.search_array);
//
//                bundle.putString(SearchActivity.TAG_ITEM, languages[0]);
//                bundle.putString(SearchActivity.TAG_KEY, query);
//                intent.putExtras(bundle);
//                startActivity(intent);
//                return true;
//            }
//
//            public boolean onQueryTextChange(String newText) {
//                return true;
//            }
//        });


//        Log.d("Tag", "menu create");
//        MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener() {//设置打开关闭动作监听
//            @Override
//            public boolean onMenuItemActionExpand(MenuItem item) {
//                Toast.makeText(Main2Activity.this, "onExpand", Toast.LENGTH_LONG).show();
//                return true;
//            }
//
//            @Override
//            public boolean onMenuItemActionCollapse(MenuItem item) {
//                Toast.makeText(Main2Activity.this, "Collapse", Toast.LENGTH_LONG).show();
//                return true;
//            }
//        });
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * DrawerLayout状态变化监听
     */
    private class DrawerLayoutStateListener extends
            DrawerLayout.SimpleDrawerListener {
        /**
         * 当导航菜单滑动的时候被执行
         */
        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            if (drawerView == right_drawer) {
                // 根据isDirection_right决定执行动画
                //mMaterialMenuIcon.setTransformationOffset(
                //MaterialMenuDrawable.AnimationState.BURGER_ARROW,
                //isDirection_right ? 2 - slideOffset : slideOffset);
            }
        }

        /**
         * 当导航菜单打开时执行
         */
        @Override
        public void onDrawerOpened(View drawerView) {
            if (drawerView == right_drawer) {
                isDirection_right = true;
            }
        }

        /**
         * 当导航菜单关闭时执行
         */
        @Override
        public void onDrawerClosed(View drawerView) {
            if (drawerView == right_drawer) {
                isDirection_right = false;
//                showView = mMenuListView;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case 1003:
                onTabSelected(4);
                break;
            default:
                break;
        }

    }

    private BackHandledFragment mBackHandedFragment;

    @Override
    public void setSelectedFragment(BackHandledFragment selectedFragment) {
        this.mBackHandedFragment = selectedFragment;
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            }
            else
            {
                ActivityManager manager = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE); //获取应用程序管理器
                manager.killBackgroundProcesses(getPackageName()); //强制结束当前应用程序
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setMessageIcon() {
        String token = SystemSet.getInstance().getToken();
        if (token != null && token.length() > 0 && !token.equals("")) {
            ServerApi.message_count(token, new ServerCallBack() {
                @Override
                public void onError(Request request, Exception e) {
                    numberBadgeItem.hide();
                }

                @Override
                public void onResponse(String response) throws JSONException {
                    JSONObject jsonObject = new JSONObject(response);
                    int date = jsonObject.optInt("data");
                    if (date != 0) {
                        Log.e("data", response);
                        if (date > 0) {
                            if (mineItem != null) {
                                numberBadgeItem.setBorderWidth(2)
                                        .setBackgroundColorResource(R.color.colorAccent)
                                        .setText("" + date)
                                        .setHideOnSelect(true);
                            } else {
                                hideBrbtn();
                            }
                        }
                    }
                }
            });
        }
    }

    private void hideBrbtn()
    {
        if (numberBadgeItem != null){
            numberBadgeItem.setBackgroundColor(android.R.color.transparent);
            numberBadgeItem.hide();
        }

    }

    @Override
    protected void onRestart()
    {
        super.onRestart();
        setMessageIcon();
    }
}
